﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Windows.Controls.Ribbon;
using The.NET_Downloader.Download;
using System.Collections.ObjectModel;
using MyDownloader.Core;
using System.ComponentModel;

namespace The.NET_Downloader
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : RibbonWindow
    {
        public ReadOnlyCollection<Downloader> DownloadList
        {
            get
            {
                return downloadManager.Downloads;
            }
        }

        public double ProgressBarValue
        {
            get
            {
                return progressBar1.Value / progressBar1.Maximum;
            }
        }


        MyDownloader.Core.DownloadManager downloadManager = MyDownloader.Core.DownloadManager.Instance;

        const int UPDATETIME = 2000; //Update every 2 seconds

        BackgroundWorker worker = new BackgroundWorker();

        MyDownloader.Extension.PersistedList.PersistedListExtension PersistantList;

        public MainWindow()
        {
           
            InitializeComponent();
            worker.DoWork += new DoWorkEventHandler(worker_DoWork);
            worker.RunWorkerAsync();
            progressBar1.Value = 0;
            progressBar1.Minimum = 0;
            progressBar1.Maximum = 100;
            downloadManager.DownloadEnded += new EventHandler<DownloaderEventArgs>(downloadManager_DownloadEnded);
            downloadManager.DownloadRemoved += new EventHandler<DownloaderEventArgs>(downloadManager_DownloadRemoved);
        }

        void downloadManager_DownloadRemoved(object sender, DownloaderEventArgs e)
        {
          //  RemoveDownload(e.Downloader);
        }

        void downloadManager_DownloadEnded(object sender, DownloaderEventArgs e)
        {
           // RemoveDownload(e.Downloader);
        }

        void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            while (true)
            {
                System.Threading.Thread.Sleep(UPDATETIME);
                UpdateDisplay();
            }
        }

        void updateTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
        
            
        }

        private void RibbonWindow_Loaded(object sender, RoutedEventArgs e)
        {
            
          /*  MyDownloader.Extension.Protocols.BaseProtocolProvider a = new MyDownloader.Extension.Protocols.BaseProtocolProvider();
            MyDownloader.Extension.Protocols.HttpFtpProtocolExtension b = new MyDownloader.Extension.Protocols.HttpFtpProtocolExtension();
            MyDownloader.Extension.Protocols.HttpFtpProtocolParametersSettingsProxy c = new MyDownloader.Extension.Protocols.HttpFtpProtocolParametersSettingsProxy();*/
            PersistantList = new MyDownloader.Extension.PersistedList.PersistedListExtension();
            List<object> extensions = new List<object>();
            extensions.Add(new MyDownloader.Extension.Protocols.HttpFtpProtocolExtension());
            extensions.Add(new MyDownloader.Extension.Video.VideoDownloadExtension());
            extensions.Add(new MyDownloader.Extension.SpeedLimit.SpeedLimitExtension());
            extensions.Add(PersistantList);

            UpdateDisplay();

            if (TaskbarItemInfo == null)
                TaskbarItemInfo = new System.Windows.Shell.TaskbarItemInfo();
        }

        private void Ribbon_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (Ribbon.SelectedItem == OptionsTab)
            {
                //Load Options

            }
            if (Ribbon.SelectedItem == HistoryTab)
            {
                downloadsListView.Visibility = System.Windows.Visibility.Collapsed;
                TestView.Visibility = System.Windows.Visibility.Visible;
            }
            else
            {
                if (downloadsListView == null)
                    return;
                downloadsListView.Visibility = System.Windows.Visibility.Visible;
                TestView.Visibility = System.Windows.Visibility.Collapsed;
            }
        }

        private void UpdateDisplay()
        {
            
            double averageProgress = 0;
            foreach (Downloader a in downloadManager.Downloads)
            {
                averageProgress += a.Progress;
            }
            averageProgress /= downloadManager.Downloads.Count;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

            System.Threading.Thread thread = new System.Threading.Thread(
              new System.Threading.ThreadStart(
                delegate()
                {
                    speedlabel.Dispatcher.Invoke(
                      System.Windows.Threading.DispatcherPriority.Normal,
                      new Action(
                        delegate()
                        {
                            speedlabel.Content = "Speed: " + (int)(downloadManager.TotalDownloadRate / 1024) + " kb/s";
                        }
                    ));
                }
            ));

            System.Threading.Thread thread2 = new System.Threading.Thread(
              new System.Threading.ThreadStart(
                delegate()
                {
                    downloadsListView.Dispatcher.Invoke(
                      System.Windows.Threading.DispatcherPriority.Normal,
                      new Action(
                        delegate()
                        {
                            downloadsListView.ItemsSource = DownloadList;
                            downloadsListView.Items.Refresh();
                        }
                    ));
                }
            ));
            System.Threading.Thread thread3 = new System.Threading.Thread(
              new System.Threading.ThreadStart(
                delegate()
                {
                    progressBar1.Dispatcher.Invoke(
                      System.Windows.Threading.DispatcherPriority.Normal,
                      new Action(
                        delegate()
                        {
                            if(!double.IsNaN(averageProgress))
                                progressBar1.Value = averageProgress;
                            
                            TaskbarItemInfo.ProgressValue = ProgressBarValue;
                            if (downloadManager.ActiveDownloads > 0)
                                TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Normal;
                            else
                                TaskbarItemInfo.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
                        }
                    ));
                }
            ));

            thread.Start();
            thread2.Start();
            thread3.Start();

        }

        private void btnNewDownload_Click(object sender, RoutedEventArgs e)
        {
            NewDownloadWindow newDownloadWindows = new NewDownloadWindow();
            newDownloadWindows.Owner = this;
            
            if (newDownloadWindows.ShowDialog() == true)
            {
                Uri add = newDownloadWindows.DownloadUri;
                AddDownload(add);
           
            }
        }

        private void AddDownload(Uri u)
        {
            ResourceLocation location = ResourceLocation.FromURL(u.ToString());
            string localFile = GetLocalFileName(u);
            Downloader downloader = downloadManager.Add(location, null, localFile, 100);
            downloader.Start();
            UpdateDisplay();
            
        }

        private string GetLocalFileName(Uri remoteUri)
        {
            string filename = remoteUri.Segments[remoteUri.Segments.Length - 1];

            filename = Uri.UnescapeDataString(filename);
            if (filename.Length > 150)
                filename = filename.Substring(filename.Length - 150);

            return new System.IO.DirectoryInfo(Properties.Settings.Default.DownloadFolder).FullName + "\\" + filename;
        }

        private void button1_Click(object sender, RoutedEventArgs e)
        {
            
        }

        private void RibbonWindow_Closing(object sender, CancelEventArgs e)
        {
            PersistantList.PersistList(null);
            downloadManager.PauseAll();
        }

        private void btnForceStart_Click(object sender, RoutedEventArgs e)
        {
            foreach (Downloader item in downloadsListView.SelectedItems)
            {
                item.Pause();
                item.Start();       
            }
            UpdateDisplay();
        }

        private void btnPauseAll_Click(object sender, RoutedEventArgs e)
        {
            foreach (Downloader item in downloadsListView.SelectedItems)
            {
                item.Pause();
            }
            UpdateDisplay();
        }

        private void btnDeleteDownload_Click(object sender, RoutedEventArgs e)
        {
            foreach (Downloader item in downloadsListView.SelectedItems)
            {
                downloadManager.RemoveDownload(item);
            }
            UpdateDisplay();
        }

        private void MenuItemtExit_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void MenuItemAbout_Click(object sender, RoutedEventArgs e)
        {
            new About() { Owner = this }.ShowDialog();
        }

        private void ButtonAdvancedOptions_Click(object sender, RoutedEventArgs e)
        {
            new OptionsWindow() { Owner = this }.ShowDialog();
        }

        private void button1_Click_1(object sender, RoutedEventArgs e)
        {
           
        }

        private void downloadsListView_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (downloadsListView.SelectedItem == null)
                    return;
                System.Diagnostics.Process.Start((downloadsListView.SelectedItem as Downloader).LocalFile);
            }
            catch
            {
            }
        }

        private void MenuItem_Click(object sender, RoutedEventArgs e)
        {
            new DownloadInformationWindow(downloadsListView.SelectedItem as Downloader) { Owner = this }.ShowDialog();
        }



        
    }
}
